package cn.dnf.service.impl;

import cn.dnf.domain.Relation;
import cn.dnf.domain.Ticket;
import cn.dnf.domain.User;
import cn.dnf.enums.GlobalEnumCode;
import cn.dnf.exception.GlobalCustomException;
import cn.dnf.mapper.MovieMapper;
import cn.dnf.mapper.RelationMapper;
import cn.dnf.service.IMovieService;
import cn.dnf.util.JsonResult;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

@Service
public class MovieServiceImpl implements IMovieService {
    @Resource
    private MovieMapper movieMapper;
    @Resource
    private RelationMapper relationMapper;


    @Override
    public List<Ticket> findAll() {
        return movieMapper.findAll();
    }

    @Override
    public Ticket findById(Long id) {
        return movieMapper.findById(id);
    }

    @Override
    public void update(Ticket ticket) {
        Relation relation = new Relation();
        relation.setUser_id(1L);
        relation.setMovie_ticket_id(ticket.getId());
        relation.setStatus(0L);
        relationMapper.add(relation);
    movieMapper.update(ticket);
    }

    @Override
    public JsonResult watch(Long id) {

            Relation relation = relationMapper.selectByMovieId(id);
            if(relation.getStatus()==0) {
                relation.setStatus(1L);
                relationMapper.update(relation);
                return JsonResult.success().setMessage("观影成功");
            }
            else{
                return JsonResult.success().setMessage("没有有效影票");
            }

    }

    @Override
    public void gift(User user) {
        Relation relation = new Relation();
        relation.setUser_id(user.getId());
        relation.setStatus(0L);
        relation.setMovie_ticket_id(RandomUtils.nextInt(movieMapper.count()));
        relationMapper.add(relation);
        Ticket ticket = movieMapper.findById(1L);
        ticket.setStock(ticket.getStock()-1);
        movieMapper.update(ticket);

    }


}
